from django.shortcuts import render
from rest_framework import viewsets
from rest_framework import mixins
from rest_framework.permissions import IsAuthenticated
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework.authentication import SessionAuthentication

from .models import UserFav, UserLeavingMessage, UserAddress
from utils.permissions import IsOwnerOrReadOnly
from .serializers import UserFavSerializer, UserFavDetailSerializer
from .serializers import LeavingMessageSerializer, AddressSerializer


# Create your views here.


# class UserFavViewSet(mixins.CreateModelMixin, mixins.ListModelMixin, mixins.DestroyModelMixin, viewsets.GenericViewSet):
class UserFavViewSet(viewsets.ModelViewSet):
    """
    list:
        获取用户收藏列表
    retrieve:
        判断某个商品是否已经收藏
    create:
        收藏商品
    destroy:
        取消收藏
    """
    # queryset = UserFav.objects.all()
    permission_classes = (IsAuthenticated, IsOwnerOrReadOnly,)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication,)
    lookup_field = 'goods_id'

    # 用户收藏，在点击收藏和展示收藏时序列化类不一样
    # serializer_class = UserFavSerializer
    def get_serializer_class(self):
        if self.action == "list":
            return UserFavDetailSerializer
        if self.action == "create":
            return UserFavSerializer
        return UserFavSerializer

    def perform_create(self, serializer):
        serializer.save()
        # 已将使用signal的方式实现了收藏数加1，此处就不需要了.
        # instance = serializer.save()
        # goods = instance.goods
        # goods.fav_num += 1
        # goods.save()

    def perform_destroy(self, instance):
        instance.delete()
        # 已将使用signal的方式实现了取消收藏时减1，此处就不需要了.
        # goods = instance.goods
        # goods.fav_num -= 1
        # goods.save()

    def get_queryset(self):
        return UserFav.objects.filter(user=self.request.user)


class LeavingMessageViewSet(mixins.ListModelMixin, mixins.DestroyModelMixin, mixins.CreateModelMixin,
                            viewsets.GenericViewSet):
    """
    list:
        获取用户留言
    create:
        添加留言
    delete:
        删除留言
    """
    permission_classes = (IsAuthenticated, IsOwnerOrReadOnly,)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication,)
    serializer_class = LeavingMessageSerializer

    def get_queryset(self):
        return UserLeavingMessage.objects.filter(user=self.request.user)


class AddressViewSet(viewsets.ModelViewSet):
    """
    收货地址管理
    list:
        获取收货地址
    create:
        添加收货地址
    update:
        更新收货地址
    delete:
        删除收货地址
    """
    permission_classes = (IsAuthenticated, IsOwnerOrReadOnly,)
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication,)
    serializer_class = AddressSerializer

    def get_queryset(self):
        return UserAddress.objects.filter(user=self.request.user)
